package com.css.zfzx.sjcj.modules.hddcRSInterpretationLine.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.spacedata.vo.SpaceDataParamsVo;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPlanningLine.repository.entity.HddcGeologicalsvyplanninglineEntity;
import com.css.zfzx.sjcj.modules.hddcRSInterpretationLine.repository.HddcRsinterpretationlineNativeRepository;
import com.css.zfzx.sjcj.modules.hddcRSInterpretationLine.repository.HddcRsinterpretationlineRepository;
import com.css.zfzx.sjcj.modules.hddcRSInterpretationLine.repository.entity.HddcRsinterpretationlineEntity;
import com.css.zfzx.sjcj.modules.hddcRSInterpretationLine.service.HddcRsinterpretationlineService;
import com.css.zfzx.sjcj.modules.hddcRSInterpretationLine.viewobjects.HddcRsinterpretationlineQueryParams;
import com.css.zfzx.sjcj.modules.hddcRSInterpretationLine.viewobjects.HddcRsinterpretationlineVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zhangping
 * @date 2020-11-30
 */
@Service
public class HddcRsinterpretationlineServiceImpl implements HddcRsinterpretationlineService {

	@Autowired
    private HddcRsinterpretationlineRepository hddcRsinterpretationlineRepository;
    @Autowired
    private HddcRsinterpretationlineNativeRepository hddcRsinterpretationlineNativeRepository;

    @Override
    public JSONObject queryHddcRsinterpretationlines(HddcRsinterpretationlineQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcRsinterpretationlineEntity> hddcRsinterpretationlinePage = this.hddcRsinterpretationlineNativeRepository.queryHddcRsinterpretationlines(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcRsinterpretationlinePage);
        return jsonObject;
    }


    @Override
    public HddcRsinterpretationlineEntity getHddcRsinterpretationline(String id) {
        HddcRsinterpretationlineEntity hddcRsinterpretationline = this.hddcRsinterpretationlineRepository.findById(id).orElse(null);
         return hddcRsinterpretationline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcRsinterpretationlineEntity saveHddcRsinterpretationline(HddcRsinterpretationlineEntity hddcRsinterpretationline) {
        String uuid = UUIDGenerator.getUUID();
        hddcRsinterpretationline.setUuid(uuid);
        hddcRsinterpretationline.setCreateUser(PlatformSessionUtils.getUserId());
        hddcRsinterpretationline.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcRsinterpretationline.setIsValid("1");
        hddcRsinterpretationline.setQualityinspectionStatus("0");
        hddcRsinterpretationline.setExtends10("1");
        this.hddcRsinterpretationlineRepository.save(hddcRsinterpretationline);
        return hddcRsinterpretationline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Iterable<HddcRsinterpretationlineEntity> saveHddcRsinterpretationlineList(List<HddcRsinterpretationlineEntity> list) {
        for (HddcRsinterpretationlineEntity hddcRsinterpretationline : list) {
            String uuid = UUIDGenerator.getUUID();
            hddcRsinterpretationline.setUuid(uuid);
            hddcRsinterpretationline.setCreateUser(PlatformSessionUtils.getUserId());
            hddcRsinterpretationline.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            hddcRsinterpretationline.setIsValid("1");
            hddcRsinterpretationline.setQualityinspectionStatus("0");
            hddcRsinterpretationline.setExtends10("1");
        }
        return hddcRsinterpretationlineNativeRepository.batchSave(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcRsinterpretationlineEntity updateHddcRsinterpretationline(HddcRsinterpretationlineEntity hddcRsinterpretationline) {
        HddcRsinterpretationlineEntity entity = hddcRsinterpretationlineRepository.findById(hddcRsinterpretationline.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcRsinterpretationline);
        hddcRsinterpretationline.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcRsinterpretationline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcRsinterpretationlineRepository.save(hddcRsinterpretationline);
        return hddcRsinterpretationline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcRsinterpretationlines(List<String> ids) {
        List<HddcRsinterpretationlineEntity> hddcRsinterpretationlineList = this.hddcRsinterpretationlineRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcRsinterpretationlineList) && hddcRsinterpretationlineList.size() > 0) {
            for(HddcRsinterpretationlineEntity hddcRsinterpretationline : hddcRsinterpretationlineList) {
                hddcRsinterpretationline.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcRsinterpretationline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcRsinterpretationline.setIsValid("0");
                this.hddcRsinterpretationlineRepository.save(hddcRsinterpretationline);
            }
        }
    }

    /**
     * 逻辑删除-根据项目id删除数据
     * @param projectIds
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcRsinterpretationlineEntity> hddcRsinterpretationlineList = this.hddcRsinterpretationlineRepository.queryHddcRsinterpretationlinesByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcRsinterpretationlineList) && hddcRsinterpretationlineList.size() > 0) {
            for(HddcRsinterpretationlineEntity hddcRsinterpretationline : hddcRsinterpretationlineList) {
                hddcRsinterpretationline.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcRsinterpretationline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcRsinterpretationline.setIsValid("0");
                this.hddcRsinterpretationlineRepository.save(hddcRsinterpretationline);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     * @param taskId
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcRsinterpretationlineEntity> hddcRsinterpretationlineList = this.hddcRsinterpretationlineRepository.queryHddcRsinterpretationlinesByTaskId(taskId);
        if(!PlatformObjectUtils.isEmpty(hddcRsinterpretationlineList) && hddcRsinterpretationlineList.size() > 0) {
            for(HddcRsinterpretationlineEntity hddcRsinterpretationline : hddcRsinterpretationlineList) {
                hddcRsinterpretationline.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcRsinterpretationline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcRsinterpretationline.setIsValid("0");
                this.hddcRsinterpretationlineRepository.save(hddcRsinterpretationline);
            }
        }
    }

    @Override
    public String judegeParams(String[] datas) {
        String str = "";
        Set<String> set = new HashSet<String>(Arrays.asList(datas));
        if(!set.contains("ID")){
            str+="ID,";
        }
        if(!set.contains("GeomorphyCode")){
            str+="GeomorphyCode,";
        }
        if(!set.contains("GeomorphyType")){
            str+="GeomorphyType,";
        }
        if(!set.contains("GeomorphyName")){
            str+="GeomorphyName,";
        }
        if(!set.contains("InterpretationAccording")){
            str+="InterpretationAccording,";
        }
        if(!set.contains("CommentInfo")){
            str+="CommentInfo,";
        }
        return str;
    }

    @Override
    public void saveHddcRsinterpretationlineFromShpFiles(List<List<Object>> list, String provinceName, String cityName, String areaName,String savefilename) {
        if(list!=null&&list.size()>0){
            List<HddcRsinterpretationlineEntity> datas= new ArrayList<>();
            for(int i=0;i<list.size();i++){
                List<Object> obs=list.get(i);
                HddcRsinterpretationlineEntity data = new HddcRsinterpretationlineEntity();
                data.setArea(areaName);
                data.setProvince(provinceName);
                data.setCity(cityName);
                data.setExtends8(savefilename);
                data.setId(obs.get(1).toString());
                data.setGeomorphycode(obs.get(2).toString());
                data.setGeomorphytype(obs.get(3).toString());
                data.setGeomorphyname(obs.get(4).toString());
                data.setInterpretationaccording(obs.get(5).toString());
                data.setCommentInfo(obs.get(6).toString());
                data.setExtends16("CGCS2000");
                String pstr=obs.get(0).toString();
                /*String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }*/
                pstr = pstr.replace(")), ((", "#");
                pstr = pstr.replace("), (", "#");
                String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }
                datas.add(data);
                /*for(int j=0;j<obs.size();j++){
                    Object value=obs.
                }*/
            }
            deleteByCreateUser(provinceName,cityName,areaName);

            saveHddcRsinterpretationlineList(datas);
        }
    }

    @Override
    public List<HddcRsinterpretationlineEntity> findAll() {
        List<HddcRsinterpretationlineEntity> list=this.hddcRsinterpretationlineRepository.findAll();
        return list;
    }

    @Override
    @Transactional
    public void deleteFileData(SpaceDataParamsVo paramsVo) {
        String provinceName=paramsVo.getProvinceName();
        String cityName=paramsVo.getCityName();
        String areaName=paramsVo.getAreaName();
        String savefilename=paramsVo.getSavefilename();
        hddcRsinterpretationlineRepository.deleteFileData(provinceName,cityName,areaName,savefilename);
    }

    public void deleteByCreateUser(String provinceName,String cityName,String areaName){
        String createID=PlatformSessionUtils.getUserId();
        List<HddcRsinterpretationlineEntity> hddcRsinterpretationlineList = this.hddcRsinterpretationlineRepository.queryHddcRsinterpretationlineByCreateuser(createID,provinceName,cityName,areaName);
        if(!PlatformObjectUtils.isEmpty(hddcRsinterpretationlineList) && hddcRsinterpretationlineList.size() > 0) {
            hddcRsinterpretationlineRepository.deleteAll(hddcRsinterpretationlineList);
        }
    }
    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcRsinterpretationlineQueryParams queryParams, HttpServletResponse response) {
        List<HddcRsinterpretationlineEntity> yhDisasterEntities = hddcRsinterpretationlineNativeRepository.exportYhDisasters(queryParams);
        List<HddcRsinterpretationlineVO> list=new ArrayList<>();
        for (HddcRsinterpretationlineEntity entity:yhDisasterEntities) {
            HddcRsinterpretationlineVO yhDisasterVO=new HddcRsinterpretationlineVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "航、卫片解译线-线", "航、卫片解译线-线", HddcRsinterpretationlineVO.class, "航、卫片解译线-线.xls", response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcRsinterpretationlineVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcRsinterpretationlineVO.class, params);
            List<HddcRsinterpretationlineVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcRsinterpretationlineVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcRsinterpretationlineVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcRsinterpretationlineVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcRsinterpretationlineEntity yhDisasterEntity = new HddcRsinterpretationlineEntity();
            HddcRsinterpretationlineVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcRsinterpretationline(yhDisasterEntity);
        }
    }

}
